# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def sumNumbers(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        acc = []
        def traverse(root):
            sum = 0
            acc.append(str(root.val))
            if root.left or root.right:
                if root.left: sum += traverse(root.left)
                if root.right: sum += traverse(root.right)
            else:
                sum += int(''.join(acc))
            acc.pop()
            return sum
        return traverse(root) if root else 0